package com.wish.g04.financial.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.wish.g04.base.entity.*;
import com.wish.g04.base.service.*;
import com.wish.g04.common.core.constant.HttpStatus;
import com.wish.g04.common.core.utils.StringUtils;
import com.wish.g04.common.core.utils.bean.BeanUtils;
import com.wish.g04.common.core.web.domain.AjaxResult;
import com.wish.g04.common.core.web.page.TableDataInfo;
import com.wish.g04.common.security.utils.SecurityUtils;
import com.wish.g04.financial.dto.CfContractDto;
import com.wish.g04.financial.dto.JrRentInstallmentDTO;
import com.wish.g04.financial.service.TbJrRenInstallmentService;
import com.wish.g04.financial.vo.CfContractVo;
import com.wish.g04.financial.vo.CounterListVO;
import com.wish.g04.financial.vo.SFContractVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 申请租房分期 服务实现类
 */
@Service
public class TbJrRenInstallmentServiceImpl implements TbJrRenInstallmentService {

    // 租房
    @Autowired
    private ICfContractService iCfContractService;

    //    金融
    @Autowired
    private IJrProductService iJrProductService;

    //    租房分期申请
    @Autowired
    private IJrRentInstallmentService iJrRentInstallmentService;

    //    财务
    @Autowired
    private ICwReceiptPlanService iCwReceiptPlanService;

    @Autowired
    private IPremisesInfoService iPremisesInfoService;

    /**
     * 出房列表
     *
     * @param cfContractDto
     * @return
     */
    @Override
    public TableDataInfo getStageRentingList(CfContractDto cfContractDto) {
        QueryWrapper<CfContract> wrapper = new QueryWrapper<>();
//        前端查询条件
        if (StringUtils.isNotEmpty(cfContractDto.getPremiseName())) {
            wrapper.like("premise_name", cfContractDto.getPremiseName());
        }
        if (StringUtils.isNotEmpty(cfContractDto.getTenantName())) {
            wrapper.like("tenant_name", cfContractDto.getTenantName());
        }
//  未删除
        wrapper.eq("del_flg ", 0);
//         <!-- 未申请过租房分期 -->
        wrapper.eq("rent_installment_flg", 0);
//         <!-- 未申请过租约保理 -->
        wrapper.eq("zybl_flg", 0);
//         <!-- 合同状态是正常执行中状态 -->
        wrapper.eq("contract_state", 2);
//         <!-- 未续约 -->
        wrapper.eq("xuyue_state", 0);
//        <!-- 未冻结状态 -->
        wrapper.eq("freeze_status", 0);
//        <!-- 合同开始日大于等于当前日期 -->
        wrapper.ge("DATEDIFF(NOW(), start_date)", 0);
        wrapper.orderByDesc("id");

        List<CfContract> list = iCfContractService.list(wrapper);
        TableDataInfo dataTable = getDataTable(list);

        ArrayList<CfContractVo> cfContractVos = new ArrayList<>();
        for (CfContract cfContract : list) {
            CfContractVo cfContractVo = new CfContractVo();
            BeanUtils.copyProperties(cfContract, cfContractVo);
            cfContractVos.add(cfContractVo);
        }
        dataTable.setRows(cfContractVos);
        return dataTable;
    }

    @Override
    public AjaxResult getJRAProductList(Integer jrProductType) {
        QueryWrapper<JrProduct> wrapper = new QueryWrapper<>();
//        类型
        wrapper.eq("jr_product_type", jrProductType);
//        可用状态
        wrapper.eq("del_flg", 0);
        wrapper.eq("auditor_status", 0);//审核通过
        List<JrProduct> list = iJrProductService.list(wrapper);
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult getRentingContract(Integer id) {
        HashMap<String, Object> map = new HashMap<>();
//        查询租房合同表
        CfContract cfContract = iCfContractService.getById(id);
//        总金额
        int startDate = cfContract.getStartDate().getMonthValue();
        int endDate = cfContract.getEndDate().getMonthValue();
        int startYear = cfContract.getStartDate().getYear();
        int endYear = cfContract.getEndDate().getYear();
        int month = (endYear - startYear) * 12;//差年换算成月
        if (endDate >= startDate) {
            month += endDate - startDate;
        } else {
            month -= endDate - startDate;
        }
        int day1 = cfContract.getStartDate().getDayOfMonth();
        int day2 = cfContract.getEndDate().getDayOfMonth();
        if (day2 >= day1) {
            month += 1;
        }

        double monthRent = cfContract.getMonthRent().doubleValue();
        double loanAmount = monthRent * month;
        map.put("data", cfContract);
        map.put("loanAmount", loanAmount);
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult saveStageRenting(JrRentInstallmentDTO jrRentInstallmentDto) {
        JrRentInstallment jrRentInstallment = new JrRentInstallment();
        BeanUtils.copyProperties(jrRentInstallmentDto, jrRentInstallment);

        jrRentInstallment.setCfContractId(jrRentInstallmentDto.getId())
                .setApplyState(1)//申请状态
                .setCreateTime(LocalDateTime.now())//创建时间
                .setRentInstallmentOrderNo("FZFQ" + RandomUtil.randomNumbers(18))//分期随机编号
                .setOutOrderNo(jrRentInstallmentDto.getCfContractNo())//出房合同编号
                .setCfContractId(jrRentInstallmentDto.getId())//厨房合同id
                //        添加到租房分期表 t_jr_rent-installment
                .setApplyState(1)//申请中
                .setBussinessId(jrRentInstallmentDto.getBusinessId() + "")//商户id
                .setCreateUserid(SecurityUtils.getUserId())//用户id
                .setUpdateUserid(SecurityUtils.getUserId())//用户id
                .setUpdateTime(LocalDateTime.now());//修改时间
        iJrRentInstallmentService.saveOrUpdate(jrRentInstallment);//添加租房分期申请

        CfContract byId = iCfContractService.getById(jrRentInstallment.getCfContractId());//获取合同对象
        iCfContractService.saveOrUpdate(byId.setFreezeStatus(true).setUpdateTime(LocalDateTime.now()));//冻结。修改时间


        List<CwReceiptPlan> list = getCwReceiptPlanList(jrRentInstallmentDto);//获取要添加的集合，或修改的集合
        iCwReceiptPlanService.saveOrUpdateBatch(list);
        return AjaxResult.success();
    }

    private List<CwReceiptPlan> getCwReceiptPlanList(JrRentInstallmentDTO jrRentInstallmentDto) {
//        查找合同
        CfContract byIdCfContract = iCfContractService.getById(jrRentInstallmentDto.getId());
//        查找对应楼盘id
        QueryWrapper<PremisesInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("name", byIdCfContract.getPremiseName())
                .select("id", "name");
        PremisesInfo onePremisesInfo = iPremisesInfoService.getOne(wrapper);


        LocalDateTime startDate = byIdCfContract.getStartDate();
        LocalDateTime endDate = byIdCfContract.getEndDate();
        LocalDateTime dd = startDate;
        ArrayList<CwReceiptPlan> list = new ArrayList<>();
        Integer no = 1;
        while (dd.isBefore(endDate)) {//时间小于结束时间
            CwReceiptPlan cwReceiptPlan = new CwReceiptPlan();
            BeanUtils.copyProperties(jrRentInstallmentDto, cwReceiptPlan);

            //        赋值
            cwReceiptPlan.setId(null)
                    .setContractType(2)//合同类型
                    .setContractId(byIdCfContract.getId())//合同id
                    .setContractNo(byIdCfContract.getCfContractNo())//租房合同编号
                    .setPremiseId(Long.valueOf(onePremisesInfo.getId()))//楼盘id
                    .setPremiseName(onePremisesInfo.getName())//楼盘name
                    .setReceiptType(1)//收款类型 房屋收款
                    .setSkStatus(4)//收款状态 冻结
                    .setReceiptNumber(no)//第几期
                    .setReceiptOrderNo("SKJH" + RandomUtil.randomNumbers(18))//收款计划
                    .setBusinessId(jrRentInstallmentDto.getBusinessId())//商户id
                    .setCreateUserid(SecurityUtils.getUserId())
                    .setUpdateUserid(SecurityUtils.getUserId())
                    .setCreateTime(LocalDateTime.now())
                    .setUpdateTime(LocalDateTime.now())
                    .setBillType(4)//账单类型
                    .setItemType(3);//房租

            //时间等于开始时间
            if (dd.isEqual(startDate)) {
                cwReceiptPlan.setPaymentDaysBegin(dd);
                cwReceiptPlan.setCollectionDate(dd);
                dd = dd.plusMonths(1);//月+1
                dd = dd.minusDays(-1);//日-1
                cwReceiptPlan.setPaymentDaysEnd(dd);
            } else {
                dd = dd.plusDays(1);
                cwReceiptPlan.setPaymentDaysBegin(dd);
                cwReceiptPlan.setCollectionDate(dd);

                dd = dd.plusMonths(1);
                if (dd.isBefore(endDate) || dd.isEqual(endDate)) {
                    dd.minusDays(-1);
                    cwReceiptPlan.setPaymentDaysEnd(dd);
                } else {
                    cwReceiptPlan.setPaymentDaysEnd(LocalDateTime.from(endDate));
                }
            }
            list.add(cwReceiptPlan);
            no++;
        }
        return list;
    }

    @Override
    public AjaxResult counter(JrRentInstallmentDTO jrRentInstallmentDto) {
        HashMap<String, Object> map = new HashMap<>();
//        租房合同
        CfContract cfContract = iCfContractService.getById(jrRentInstallmentDto.getId());
        int startDate = cfContract.getStartDate().getMonthValue();
        int endDate = cfContract.getEndDate().getMonthValue();
        int startYear = cfContract.getStartDate().getYear();
        int endYear = cfContract.getEndDate().getYear();
        BigDecimal monthRent = cfContract.getMonthRent();//月租金
        int month = (endYear - startYear) * 12;//差年换算成月
        if (endDate >= startDate) {
            month += endDate - startDate;
        } else {
            month -= endDate - startDate;
        }
        int day1 = cfContract.getStartDate().getDayOfMonth();
        int day2 = cfContract.getEndDate().getDayOfMonth();
        if (day2 >= day1) {
            month += 1;
        }
        BigDecimal loanAmount = new BigDecimal(month).multiply(monthRent);//总金额

        JrProduct jrProduct = iJrProductService.getById(jrRentInstallmentDto.getJrProductId());
        Long instalmentPeriod = jrProduct.getInstalmentPeriod();//产品租期

        // 每月租金 = （总金额 / 期数）
        BigDecimal stageMonthRent = monthRent;//月租金

        // 每月利息 = 每月租金 * （一次性服务 + 利率）
        BigDecimal rate = jrRentInstallmentDto.getRate().multiply(BigDecimal.valueOf(0.01));//利率
        BigDecimal serviceFee = jrRentInstallmentDto.getServiceFee().multiply(BigDecimal.valueOf(0.01));//一次性服务
        BigDecimal inInterest = stageMonthRent.multiply(rate.add(serviceFee));//每月利息
        // 每月净值 = 每月租金 - 每月利息
        BigDecimal stageMonthRentJing = stageMonthRent.subtract(inInterest);//每月净值

//        列表集合时间
        LocalDate startTime = cfContract.getStartDate().toLocalDate();
        LocalDate endTime = cfContract.getEndDate().toLocalDate();
        LocalDate dd = startTime;
//        计算机数据列表集合
        ArrayList<CounterListVO> counterListVos = new ArrayList<>();
        int no = 1;//序号
        //        计算器表单
        CounterListVO counterListVo = new CounterListVO();
        BigDecimal creditLine = jrProduct.getCreditLine().multiply(BigDecimal.valueOf(0.01));//授信额度
        BigDecimal reLeaseCount = loanAmount.multiply(creditLine);//应收租金金额授信后
        counterListVo.setReLeaseCount(reLeaseCount + "");
        BigDecimal coHirerentCount = new BigDecimal(0);//实收分期后租金金额

//            服务费总 = 总额 * (服务费、公寓、利率等) / 12 * 期数
        double serviceFeeCount = loanAmount.multiply(serviceFee).doubleValue() / 12 * month;
        counterListVo.setSerCharge(new BigDecimal(serviceFeeCount));//服务费
        //        分期利息合计
        double inInterestCount = 0;//每月利息综合

        while (dd.isBefore(endTime)) {//时间小于结束时间
            CounterListVO counterList = new CounterListVO();
            counterList.setNo(no)
                    .setRoomName(cfContract.getRoomName())//房产信息
                    .setHouseId(cfContract.getRoomCode())//房源编号
                    .setMonthRent(stageMonthRent)//应收月租金
                    .setStageMonthRent(stageMonthRentJing)//分期后月租金
                    .setInInterest(inInterest.doubleValue());//分期利息
            coHirerentCount = coHirerentCount.add(stageMonthRentJing);//实收租房分期后租金总
            inInterestCount += inInterest.doubleValue();//实收租房分期后利息总
            //时间等于开始时间
            if (dd.isEqual(startTime)) {
                counterList.setStartDate(dd);
                dd = dd.plusMonths(1);//月+1
                dd = dd.minusDays(-1);//日-1
                counterList.setEndDate(dd);
            } else {
                dd = dd.plusDays(1);
                counterList.setStartDate(dd);
                dd = dd.plusMonths(1);

                if (dd.isBefore(endTime) || dd.isEqual(endTime)) {
                    dd.minusDays(-1);
                    counterList.setEndDate(dd);
                } else {
                    counterList.setEndDate(endTime);
                }
            }
            counterListVos.add(counterList);
            no++;
        }

        counterListVo.setCoHirerentCount(coHirerentCount + "");
        counterListVo.setInInterestCount(inInterestCount + "");
        counterListVo.setHouseId(cfContract.getHouseId());

        map.put("counterList", counterListVos);
        map.put("counterVo", counterListVo);
        return AjaxResult.success(map);
    }


    @Autowired
    private ISfContractService iSfContractService;

    @Autowired
    private IJrSfLoanService iJrSfLoanService;

    @Autowired
    private ICwPaymentPlanService iCwPaymentPlanService;

    /**
     * 收房列表
     *
     * @param sfContract
     * @return
     */
    @Override
    public TableDataInfo getSFContractList(SfContract sfContract) {
        QueryWrapper<SfContract> wrapper = new QueryWrapper<>();
//        前端查询条件
        if (StringUtils.isNotEmpty(sfContract.getPremiseName())) {
            wrapper.like("premise_name", sfContract.getPremiseName());
        }
        if (StringUtils.isNotEmpty(sfContract.getOwnerName())) {
            wrapper.like("owner_name", sfContract.getOwnerName());
        }
//  未删除
        wrapper.eq("del_flg ", 0);
//         <!-- 未收房贷 -->
        wrapper.eq("sf_loan_flg", 0);
//         <!-- 合同状态是正常执行中状态 -->
        wrapper.eq("status", 2);
//        <!-- 未冻结状态 -->
        wrapper.eq("freeze_status", 0);
        //         <!-- 未续约 -->
        wrapper.eq("xy_status", 0);
//        <!-- 合同开始日大于等于当前日期 -->
        wrapper.ge("DATEDIFF(NOW(), lease_start_time)", 0);
        wrapper.orderByDesc("id");

        List<SfContract> list = iSfContractService.list(wrapper);
        TableDataInfo dataTable = getDataTable(list);

        ArrayList<SFContractVO> sfContractVos = new ArrayList<>();
        for (SfContract sfContract2 : list) {
            SFContractVO sfContractVO = new SFContractVO();
            BeanUtils.copyProperties(sfContract2, sfContractVO);
            sfContractVos.add(sfContractVO);
        }
        dataTable.setRows(sfContractVos);
        return dataTable;
    }

    @Override
    public AjaxResult getSFContractById(Integer id) {
        HashMap<String, Object> map = new HashMap<>();
//        查询租房合同表
        SfContract sfContract = iSfContractService.getById(id);
//        总金额
        int startMonth = sfContract.getLeaseStartTime().getMonth();
        int endMonth = sfContract.getLeaseEndTime().getMonth();
        int startYear = sfContract.getLeaseStartTime().getYear();
        int endYear = sfContract.getLeaseEndTime().getYear();
        int month = (endYear - startYear) * 12;//差年换算成月
        if (endMonth >= startMonth) {
            month += endMonth - startMonth;
        } else {
            month -= endMonth - startMonth;
        }
        int day1 = sfContract.getLeaseEndTime().getDay();
        int day2 = sfContract.getLeaseEndTime().getDay();
        if (day2 >= day1) {
            month += 1;
        }

        double monthRent = sfContract.getMonthRent().doubleValue();
        double loanAmount = monthRent * month;
        sfContract.setHouseName(sfContract.getPremiseName() + sfContract.getHouseName());
        map.put("data", sfContract);
        map.put("loanAmount", loanAmount);
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult SFcounter(JrRentInstallmentDTO jrRentInstallmentDto) {
        HashMap<String, Object> map = new HashMap<>();
//        租房合同
        SfContract sfContract = iSfContractService.getById(jrRentInstallmentDto.getId());
        //        总金额
        int startMonth = sfContract.getLeaseStartTime().getMonth();
        int endMonth = sfContract.getLeaseEndTime().getMonth();
        int startYear = sfContract.getLeaseStartTime().getYear();
        int endYear = sfContract.getLeaseEndTime().getYear();
        int month = (endYear - startYear) * 12;//差年换算成月
        if (endMonth >= startMonth) {
            month += endMonth - startMonth;
        } else {
            month -= endMonth - startMonth;
        }
        int day1 = sfContract.getLeaseEndTime().getDay();
        int day2 = sfContract.getLeaseEndTime().getDay();
        if (day2 >= day1) {
            month += 1;
        }

        BigDecimal monthRent = sfContract.getMonthRent();
        BigDecimal loanAmount = new BigDecimal(month).multiply(monthRent);//总金额

        JrProduct jrProduct = iJrProductService.getById(jrRentInstallmentDto.getJrProductId());
        Long instalmentPeriod = jrProduct.getInstalmentPeriod();//产品租期

        // 每月租金 = （总金额 / 期数）
        BigDecimal stageMonthRent = monthRent;//月租金

        // 每月利息 = 每月租金 * （一次性服务 + 利率）
        BigDecimal rate = jrRentInstallmentDto.getRate().multiply(BigDecimal.valueOf(0.01));//利率
        BigDecimal serviceFee = jrRentInstallmentDto.getServiceFee().multiply(BigDecimal.valueOf(0.01));//一次性服务
        BigDecimal inInterest = stageMonthRent.multiply(rate.add(serviceFee));//每月利息
        // 每月净值 = 每月租金 - 每月利息
        BigDecimal stageMonthRentJing = stageMonthRent.subtract(inInterest);//每月净值

//        列表集合时间
        LocalDate startTime = sfContract.getLeaseStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate endTime = sfContract.getLeaseEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate dd = startTime;
//        计算机数据列表集合
        ArrayList<CounterListVO> counterListVos = new ArrayList<>();
        int no = 1;//序号
        //        计算器表单
        CounterListVO counterListVo = new CounterListVO();
        BigDecimal creditLine = jrProduct.getCreditLine().multiply(BigDecimal.valueOf(0.01));//授信额度
        BigDecimal reLeaseCount = loanAmount.multiply(creditLine);//应收租金金额授信后
        counterListVo.setReLeaseCount(reLeaseCount + "");
        BigDecimal coHirerentCount = new BigDecimal(0);//实收分期后租金金额

//            服务费总 = 总额 * (服务费、公寓、利率等) / 12 * 期数
        double serviceFeeCount = loanAmount.multiply(serviceFee).doubleValue() / 12 * month;
        counterListVo.setSerCharge(new BigDecimal(serviceFeeCount));//服务费
        //        分期利息合计
        double inInterestCount = 0;//每月利息综合

        while (dd.isBefore(endTime)) {//时间小于结束时间
            CounterListVO counterList = new CounterListVO();
            counterList.setNo(no)
                    .setRoomName(sfContract.getPremiseName() + sfContract.getHouseName())//房产信息
                    .setHouseId(sfContract.getHouseId())//房源编号
                    .setMonthRent(stageMonthRent)//应收月租金
                    .setStageMonthRent(stageMonthRentJing)//分期后月租金
                    .setInInterest(inInterest.doubleValue());//分期利息
            coHirerentCount = coHirerentCount.add(stageMonthRentJing);//实收租房分期后租金总
            inInterestCount += inInterest.doubleValue();//实收租房分期后利息总
            //时间等于开始时间
            if (dd.isEqual(startTime)) {
                counterList.setStartDate(dd);
                dd = dd.plusMonths(1);//月+1
                dd = dd.minusDays(-1);//日-1
                counterList.setEndDate(dd);
            } else {
                dd = dd.plusDays(1);
                counterList.setStartDate(dd);
                dd = dd.plusMonths(1);

                if (dd.isBefore(endTime) || dd.isEqual(endTime)) {
                    dd.minusDays(-1);
                    counterList.setEndDate(dd);
                } else {
                    counterList.setEndDate(endTime);
                }
            }
            counterListVos.add(counterList);
            no++;
        }

        counterListVo.setCoHirerentCount(coHirerentCount + "");
        counterListVo.setInInterestCount(inInterestCount + "");
        counterListVo.setHouseId(sfContract.getHouseId());

        map.put("counterList", counterListVos);
        map.put("counterVo", counterListVo);

        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult saveSfContractStage(JrRentInstallmentDTO jrRentInstallmentDto) {
        JrSfLoan jrSfLoan = new JrSfLoan();

        JrProduct byIdJrProduct = iJrProductService.getById(jrRentInstallmentDto.getJrProductId());

        BeanUtils.copyProperties(jrRentInstallmentDto, jrSfLoan);
        jrSfLoan.setSfLoanOrderNo("SFD" + RandomUtil.randomNumbers(18))//收房贷编码
                .setSfContractId(jrRentInstallmentDto.getId())//收房合同id
                .setOutProductName(byIdJrProduct.getJrProductName())//金融产品名称
                .setApplyState(1)//申请中
                .setBusinessId(jrRentInstallmentDto.getBusinessId()+"")
                .setRpAmountCount(jrRentInstallmentDto.getCoHirerentCount())//还款总额合计
                .setAgInterestRate(jrRentInstallmentDto.getInInterestCount())//收房贷利息合计
                .setCreateUserid(SecurityUtils.getUserId())//创建用户id
                .setCreateTime(LocalDateTime.now())
                .setUpdateUserid(SecurityUtils.getUserId())
                .setUpdateTime(LocalDateTime.now());

        iJrSfLoanService.saveOrUpdate(jrSfLoan);//添加租房分期申请

        SfContract byIdSfContract = iSfContractService.getById(jrRentInstallmentDto.getId());//获取合同对象
        iSfContractService.saveOrUpdate(byIdSfContract.setFreezeStatus(true).setUpdateTime(new Date()));//冻结。修改时间

        /*QueryWrapper<CwPaymentPlan> wrapper = new QueryWrapper<>();
        wrapper.eq("contract_id",jrRentInstallmentDto.getId());
        List<CwPaymentPlan> list = iCwPaymentPlanService.list(wrapper);
        if(list==null){

        }{
            for (CwPaymentPlan cwPaymentPlan : list) {

            }
        }*/
        List<CwPaymentPlan> cwPaymentPlans = getJrSfLoadList(jrRentInstallmentDto);//获取要添加的集合，或修改的集合
        iCwPaymentPlanService.saveOrUpdateBatch(cwPaymentPlans);
        return AjaxResult.success();
    }

    private List<CwPaymentPlan> getJrSfLoadList(JrRentInstallmentDTO jrRentInstallmentDto) {
        //        查找合同
        SfContract byIdSfContract = iSfContractService.getById(jrRentInstallmentDto.getId());
        //        查找对应楼盘id
        QueryWrapper<PremisesInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("name", byIdSfContract.getPremiseName())
                .select("id", "name");
        PremisesInfo onePremisesInfo = iPremisesInfoService.getOne(wrapper);

        LocalDateTime startDate = byIdSfContract.getLeaseStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        LocalDateTime endDate = byIdSfContract.getLeaseEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        LocalDateTime dd = startDate;
        ArrayList<CwPaymentPlan> list = new ArrayList<>();
        Integer no = 1;
        while (dd.isBefore(endDate)) {//时间小于结束时间
            CwPaymentPlan cwPaymentPlan = new CwPaymentPlan();
            BeanUtils.copyProperties(jrRentInstallmentDto, cwPaymentPlan);
            //        赋值
            cwPaymentPlan.setId(null)
                    .setContractType(1)//合同类型
                    .setContractId(byIdSfContract.getId())//合同id
                    .setContractNo(byIdSfContract.getSfContractNo())//租房合同编号
                    .setPremiseId(Long.valueOf(onePremisesInfo.getId()))//楼盘id
                    .setPremiseName(onePremisesInfo.getName())//楼盘name
                    .setPayType(1)//收款类型 房屋收款
                    .setPayState(4)//收款状态 冻结
                    .setPayNumber(no)//第几期
                    .setPayOrderNo("FKJH" + RandomUtil.randomNumbers(18))//收款计划
                    .setBusinessId(jrRentInstallmentDto.getBusinessId())//商户id
                    .setCreateUserid(SecurityUtils.getUserId())
                    .setUpdateUserid(SecurityUtils.getUserId())
                    .setCreateTime(new Date())
                    .setUpdateTime(new Date())
                    .setBillType(4)//账单类型
                    .setItemType(2);//房租

            //时间等于开始时间
            if (dd.isEqual(startDate)) {
                cwPaymentPlan.setPaymentDaysBegin(Date.from(dd.atZone(ZoneId.systemDefault()).toInstant()));
                cwPaymentPlan.setPayableDate(Date.from(dd.atZone(ZoneId.systemDefault()).toInstant()));
                dd = dd.plusMonths(1);//月+1
                dd = dd.minusDays(-1);//日-1
                cwPaymentPlan.setPaymentDaysEnd(Date.from(dd.atZone(ZoneId.systemDefault()).toInstant()));
            } else {
                dd = dd.plusDays(1);
                cwPaymentPlan.setPaymentDaysBegin(Date.from(dd.atZone(ZoneId.systemDefault()).toInstant()));
                cwPaymentPlan.setPayableDate(Date.from(dd.atZone(ZoneId.systemDefault()).toInstant()));

                dd = dd.plusMonths(1);
                if (dd.isBefore(endDate) || dd.isEqual(endDate)) {
                    dd.minusDays(-1);
                    cwPaymentPlan.setPaymentDaysEnd(Date.from(dd.atZone(ZoneId.systemDefault()).toInstant()));
                } else {
                    cwPaymentPlan.setPaymentDaysEnd(Date.from(endDate.atZone(ZoneId.systemDefault()).toInstant()));
                }
            }
            list.add(cwPaymentPlan);
            no++;
        }
        return list;
    }

    /**
     * 响应请求分页数据
     */
    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }


}
